package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.mapper.MessageMapper;
import com.fjh.springboot_01.pojo.ChatMsg;
import com.fjh.springboot_01.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Collections;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public void handleSendMessage(ChatMsg chatMsg) {
        messageMapper.saveMessage(chatMsg);
    }

    @Override
    public void handleSendNotification(String notification) {
        System.out.println("通知发送：" + notification);
    }

    @Override
    public List<ChatMsg> getChatHistory(String userId, String friendId, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        System.out.println("开始查询历史记录 - offset: " + offset + ", pageSize: " + pageSize);
        
        List<ChatMsg> messages = messageMapper.getChatHistory(userId, friendId, offset, pageSize);
        System.out.println("数据库查询结果数量: " + (messages != null ? messages.size() : 0));
        
        // 由于在数据库中是按时间降序排序的，这里需要反转列表以保持升序显示
        if (messages != null && !messages.isEmpty()) {
            Collections.reverse(messages);
            System.out.println("消息列表已反转，第一条消息时间: " + messages.get(0).getSendTime());
        }
        
        return messages;
    }
}
